<template>
  <div class="personalCenter">
    <h1>{{ $t("个人中心", "personalCenter.personalCenter") }}</h1>
    <div class="person-info">
      <div class="current-dept">
        <span
          >{{ $t("当前所在组织", "personalCenter.currentDept") }}：
          {{
            person_info.department_name ? person_info.department_name : "--"
          }}</span
        >
      </div>
      <div class="other-info">
        <div class="left-info">
          <div class="row">
            <span>{{ $t("通讯录姓名", "personalCenter.name") }}</span>
            <span>{{ person_info.employee_name }}</span>
          </div>
          <div class="row">
            <span>{{ $t("工号", "personalCenter.workId") }}</span>
            <span>{{ person_info.work_id ? person_info.work_id : "--" }}</span>
          </div>
          <div class="row">
            <span>{{ $t("职务", "personalCenter.duty") }}</span>
            <span>{{ person_info.work_id ? person_info.duty : "--" }}</span>
          </div>
          <div class="row">
            <span>{{ $t("头像", "personalCenter.avatar") }}</span>
            <div class="avater">
              <img
                :src="`/local/uploadFiles/${person_info.picture}`"
                alt=""
                width="80"
                height="80"
                v-if="person_info.picture"
              />
              <div
                v-else
                :class="['auto-avator', person_info.sex === 0 ? 'girl' : 'boy']"
              >
                {{ person_info?.employee_name?.slice(-2) }}
              </div>
              <span
                class="resetPic"
                v-if="person_info.picture"
                @click="resetPic"
                >{{ $t("恢复默认头像", "personalCenter.reset") }}</span
              >
              <div class="change-avatar">
                <el-button
                  type="primary"
                  size="medium"
                  @click="dialogVisible = true"
                  >{{ $t("上传新头像", "personalCenter.update") }}</el-button
                >
                <span>{{
                  $t("支持png和jpg格式， 建议1M以内", "personalCenter.format")
                }}</span>
              </div>
            </div>
          </div>
        </div>
        <div class="right-info">
          <div class="row">
            <span>{{ $t("组织账号", "personalCenter.account") }}</span>
            <span>{{ person_info.employee_id }}</span>
          </div>
          <div class="row">
            <span>{{ $t("组织登录密码", "personalCenter.password") }}</span>
            <el-button type="text" @click="changePasswordDialogVisible = true"
              >{{ $t("修改密码", "personalCenter.changePassword")
              }}<i class="el-icon-edit el-icon--right"></i
            ></el-button>
          </div>
          <div class="row" v-if="!dept_hide">
            <span>{{ $t("行政部门", "personalCenter.dept") }}</span>
            <div class="depts">
              <span v-for="(item, index) in all_deptment" :key="item + index">{{
                item
              }}</span>
              {{ all_deptment.length ? "" : "--" }}
            </div>
          </div>
        </div>
      </div>
    </div>
    <el-dialog
      :title="$t('上传头像', 'personalCenter.upnew')"
      :visible.sync="dialogVisible"
      @open="onOpen"
      width="40%"
      custom-class="personal-center-dialog"
      :show-close="false"
    >
      <div class="upload-pic">
        <div class="left">
          <img
            width="300"
            height="300"
            v-show="cropperImg"
            :src="cropperImg"
            alt=""
            ref="image"
          />
          <div
            v-show="!cropperImg"
            :class="['auto-avator', person_info.sex === 0 ? 'girl' : 'boy']"
          >
            {{ person_info?.employee_name?.slice(-2) }}
          </div>
          <div class="bottom">
            <el-upload
              action
              :on-preview="beforeAvatarUpload"
              :http-request="uploadFile"
              :show-file-list="false"
            >
              <el-button type="text">{{
                $t("本地上传", "personalCenter.localUp")
              }}</el-button>
            </el-upload>
            <div class="operates">
              <i
                class="el-icon-circle-plus-outline"
                @click="operate('big')"
              ></i>
              <i class="el-icon-remove-outline" @click="operate('small')"></i>
              <i class="el-icon-refresh" @click="operate('rotate')"></i>
            </div>
          </div>
        </div>
        <div class="right">
          <div class="right-img" v-show="cropperImg"></div>
          <div
            v-show="!cropperImg"
            :class="['auto-avator', person_info.sex === 0 ? 'girl' : 'boy']"
          >
            {{ person_info?.employee_name?.slice(-2) }}
          </div>
          <span>{{ $t("头像预览", "personalCenter.review") }}</span>
          <span>102 * 102</span>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">{{
          $t("取 消", "personalCenter.cancel")
        }}</el-button>
        <el-button type="primary" @click="submit">{{
          $t("确 定", "personalCenter.confirm")
        }}</el-button>
      </span>
    </el-dialog>
    <el-dialog
      :title="$t('修改组织登录密码', 'personalCenter.changeTitle')"
      :visible.sync="changePasswordDialogVisible"
      width="30%"
      custom-class="personal-changePassword-dialog"
      :show-close="false"
    >
      <el-form :model="changePasswordForm" :rules="rules" ref="passwordForm">
        <el-form-item
          :label="$t('原密码', 'personalCenter.currentP')"
          prop="currentPassword"
        >
          <el-input
            v-model="changePasswordForm.currentPassword"
            :placeholder="$t('请输入当前密码', 'personalCenter.enterC')"
            type="password"
          ></el-input>
        </el-form-item>
        <el-form-item :label="$t('新密码', 'newP')" prop="newPassword">
          <el-input
            v-model="changePasswordForm.newPassword"
            :placeholder="$t('请输入新密码', 'personalCenter.enterN')"
            type="password"
          ></el-input>
        </el-form-item>
        <el-form-item
          :label="$t('确认密码', 'personalCenter.confP')"
          prop="confirmPassword"
        >
          <el-input
            v-model="changePasswordForm.confirmPassword"
            :placeholder="$t('请输入确认密码', 'personalCenter.enterCP')"
            type="password"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="changePasswordDialogVisible = false">{{
          $t("取 消", "personalCenter.cancel")
        }}</el-button>
        <el-button type="primary" @click="confirmChange">{{
          $t("确 定", "personalCenter.confirm")
        }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import Cropper from "cropperjs";
import "cropperjs/dist/cropper.css";
import {
  changePassword,
  getAllSettingsMap,
  getFullPathDept,
  login,
  resetAvatar,
  uploadBase,
  uploadSomething,
} from "@/http/api";
export default {
  name: "personalCenter",
  data() {
    return {
      person_info: {},
      dialogVisible: false,
      cropperImg: "",
      myCropper: {},
      currentUpImg: "",
      resImg: "",
      changePasswordDialogVisible: false,
      changePasswordForm: {
        currentPassword: "",
        newPassword: "",
        confirmPassword: "",
      },
      rules: {
        currentPassword: [
          {
            required: true,
            trigger: "blur",
            validator: async (_, value, callback) => {
              if (value && value.trim()) {
                let res = await login({
                  username: this.person_info.employee_id,
                  password: value,
                  outOrg: this.person_info.tenant_id,
                });
                if (res.code !== 20041) {
                  callback(new Error("原密码输入错误"));
                }
                callback();
              } else {
                callback(new Error("请输入原密码"));
              }
            },
          },
        ],
        newPassword: [
          {
            required: true,
            validator: (_, value, callback) => {
              if (value) {
                let ISPWD =
                  /^(?=.*[0-9])(?=.*[A-Z])(?=.*[a-z])[0-9a-zA-Z]{8,20}/;
                if (ISPWD.test(value)) {
                  callback();
                } else {
                  callback(
                    new Error("密码要求8-20位, 必须包含英文大小写和数字")
                  );
                }
              } else {
                callback(new Error("请输入密码"));
              }
            },
          },
        ],
        confirmPassword: [
          {
            required: true,
            validator: (_, value, callback) => {
              if (value) {
                if (value === this.changePasswordForm.newPassword) {
                  callback();
                } else {
                  callback(new Error("两次输入的密码需一致"));
                }
              } else {
                callback(new Error("请输入确认密码"));
              }
            },
          },
        ],
      },
      all_deptment: [],
      dept_hide: true,
    };
  },
  async mounted() {
    this.person_info = JSON.parse(localStorage.getItem("userInfo"));
    if (this.person_info.picture) {
      this.cropper;
      this.cropperImg = "/local/uploadFiles/" + this.person_info.picture;
    }
    let res = await getAllSettingsMap();
    if (res.code === 20041) {
      if (!res.data.dept_hide) {
        this.dept_hide = false;
        res = await getFullPathDept(this.person_info.all_dept_id);
        if (res.code === 20041) {
          this.all_deptment = res.data;
        }
      }
    }
  },
  methods: {
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG或PNG 格式!");
      }
      return isJPG;
    },
    async uploadFile(item) {
      let FormDatas = new FormData();
      FormDatas.append("file", item.file);
      let res = await uploadSomething(FormDatas);
      if (res.code === 20011) {
        this.cropperImg = "/local/uploadFiles/" + res.data;
        this.myCropper.replace(this.cropperImg);
      }
    },
    onOpen() {
      this.dialogVisible = true;
      this.initCropper();
    },
    initCropper() {
      if (this.cropperImg) {
        this.$nextTick(() => {
          if (this.$refs.image) {
            this.myCropper = new Cropper(this.$refs.image, {
              aspectRatio: 1,
              initialAspectRatio: 1,
              viewMode: 3,
              autoCropArea: 0.7,
              preview: ".right-img",
            });
          }
        });
      }
    },
    async submit() {
      if (this.cropperImg) {
        this.resImg = this.myCropper
          .getCroppedCanvas({
            imageSmoothingQuality: "high",
          })
          ?.toDataURL("image/jpeg");
        let FormDatas = new FormData();
        FormDatas.append("file", this.resImg);
        let res = await uploadBase(FormDatas);
        if (res.code === 20031) {
          this.person_info.picture = res.data;
          localStorage.setItem("userInfo", JSON.stringify(this.person_info));
          window.location.reload();
        }
      }
    },
    async resetPic() {
      this.$confirm("确定将头像改为默认头像？", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        callback: async (action) => {
          if (action === "confirm") {
            let res = await resetAvatar();
            if (res.code === 20031) {
              this.person_info.picture = "";
              localStorage.setItem(
                "userInfo",
                JSON.stringify(this.person_info)
              );
              window.location.reload();
            }
          }
        },
      });
    },
    confirmChange() {
      this.$refs.passwordForm.validate(async (res) => {
        if (res) {
          let res = await changePassword({
            employee_id: this.person_info.employee_id,
            newPassword: this.changePasswordForm.confirmPassword,
          });
          if (res.code === 20031) {
            this.$message.success("修改密码成功");
            setTimeout(() => {
              localStorage.removeItem("userInfo");
              localStorage.removeItem("cookie");
              const watermask = document.querySelector("#watermask");
              if (watermask) {
                document.body.className = "hiddenMask";
              }
              this.$router.push("/login");
            }, 2000);
          }
        }
      });
    },
    operate(type) {
      if (type === "big") {
        this.myCropper.zoom(0.1);
      } else if (type === "small") {
        this.myCropper.zoom(-0.1);
      } else {
        this.myCropper.rotate(90);
      }
    },
  },
  watch: {
    cropperImg: function () {
      this.initCropper();
    },
  },
};
</script>
<style lang="less" scoped>
.personalCenter {
  padding: 0 40px;
  width: 100%;
  h1 {
    font-size: 14px;
    padding-bottom: 10px;
  }
  .person-info {
    background-color: #fff;
    border-radius: 6px;
    .current-dept {
      padding: 0 20px;
      line-height: 60px;
      border-bottom: 1px solid #e8eaed;
      font-size: 17px;
    }
    .other-info {
      padding: 32px 20px;
      display: flex;
      & > div {
        flex: 1;
        &:first-child {
          border-right: 1px solid #e8eaed;
        }
        &.right-info {
          padding-left: 40px;
        }
        .row {
          &:last-child {
            margin-bottom: 0;
          }
          margin-bottom: 24px;
          display: flex;
          align-items: center;
          span {
            width: 120px;
            display: inline-block;
            font-size: 14px;
            &:first-child {
              color: #8f959e;
            }
          }
          .auto-avator {
            width: 80px;
            height: 80px;
            font-size: 40px;
          }
          .avater {
            display: flex;
            align-items: center;
            img {
              border-radius: 50%;
              &:hover + .resetPic {
                display: block;
              }
            }
            .change-avatar {
              padding-left: 20px;
              display: flex;
              flex-direction: column;
              span {
                padding-top: 16px;
                color: #8f959e;
                font-size: 12px;
                white-space: nowrap;
              }
            }
            .resetPic {
              position: absolute;
              display: none;
              width: 80px;
              height: 80px;
              line-height: 80px;
              background-color: rgba(0, 0, 0, 0.6);
              border-radius: 50%;
              color: #fff;
              font-size: 12px;
              text-align: center;
              cursor: pointer;
              &:hover {
                display: block;
              }
            }
          }
        }
      }
    }
  }
}
</style>
<style lang="less">
.personal-center-dialog,
.personal-changePassword-dialog {
  border-radius: 6px;
  overflow: hidden;
  .el-dialog__header {
    background: #224585;
    padding: 17px 24px;
    .el-dialog__title {
      color: #fff;
      font-size: 16px;
    }
  }
  .el-dialog__body {
    padding: 24px;
    .upload-pic {
      display: flex;
      .left {
        width: 300px;
        height: 300px;
        .auto-avator {
          width: 300px;
          height: 300px;
          border-radius: 0;
          font-size: 70px;
        }
        .bottom {
          display: flex;
          justify-content: space-between;
          align-items: center;
          i {
            font-size: 20px;
            font-weight: 500;
            margin-left: 10px;
            cursor: pointer;
          }
        }
      }
      .right {
        flex: 1;
        display: flex;
        flex-direction: column;
        align-items: center;
        .auto-avator {
          width: 90px;
          height: 90px;
          font-size: 30px;
        }
        span:nth-child(3) {
          padding: 16px 0 8px;
        }
        .right-img {
          width: 90px;
          height: 90px;
          overflow: hidden;
          border-radius: 50%;
        }
      }
    }
  }
}
</style>
